/**
 * TelephoneValidator.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2013年10月21日
 */
package com.pshare.framework.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import com.pshare.constant.ReturnMsg;
import com.pshare.constant.SeaxConstants;
import com.pshare.enums.TelephoneMode;
import com.pshare.framework.annotation.TelephoneCheck;

/**
 * 电话号码验证
 */
public class TelephoneValidator implements ConstraintValidator<TelephoneCheck, CharSequence> {

	private static String CELLPHONE = "^\\d{11}$";
	private static String TELEPHONE = "((\\d{7,13})|^((\\d{3,4})-(\\d{7,8})|(\\d{3,4})-(\\d{7,8})-(\\d{1,4})|(\\d{7,8})-(\\d{1,4}))$)";

	private static Pattern cellphonePattern = Pattern.compile(CELLPHONE);
	private static Pattern telephonePattern = Pattern.compile(TELEPHONE);

	@Override
	public void initialize(TelephoneCheck constraintAnnotation) {
	}

	@Override
	public boolean isValid(CharSequence object, ConstraintValidatorContext constraintContext) {
		if (StringUtils.isBlank(object ))
			return true;

		String input = object.toString().trim().replaceAll(SeaxConstants.BLACKSLASH + SeaxConstants.PLUS, SeaxConstants.BLANK);
		boolean valid = false;
		Matcher	matcher = cellphonePattern.matcher(input);
				if (matcher.matches()) {
					valid = true;
				}
				String  msg = ReturnMsg.WRONG_CELLPHONE_FORMAT;
        if(!valid) {
            constraintContext.disableDefaultConstraintViolation();
            constraintContext.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
        }
        
        return valid;
	}
	
	/**
	 * 是否手机
	 * @param cellphone
	 * @return boolean
	 */
	public static boolean isCellphone(String cellphone) {
		if(StringUtils.isBlank(cellphone)) {
			return false;
		}
		Matcher matcher = cellphonePattern.matcher(cellphone);
		return matcher.matches();
	}
	
	/**
	 * 是否座机
	 * @param telephone
	 * @return boolean
	 */
	public static boolean isTelephone(String telephone) {
		if(StringUtils.isBlank(telephone)) {
			return false;
		}
		Matcher matcher = telephonePattern.matcher(telephone);
		return matcher.matches();
	}
	
	/**
	 * 是否是座机或手机号码
	 * @param telephone
	 * @return boolean
	 */
	public static boolean isTelephoneOrCellphone(String telephone) {
		if(StringUtils.isBlank(telephone)) {
			return false;
		}
		Matcher matcher1 = telephonePattern.matcher(telephone);
		if(matcher1.matches()) {
			return true;
		}
		Matcher matcher2 = cellphonePattern.matcher(telephone);
		return matcher2.matches();
	}

}
